import * as echarts from 'echarts'
import './echarts-tooltip-auto-show.ts'

/**
 * 初始化 echart
 * @param {Object} chart
 * @param {Object} element 元素
 * @param {Object} chartBox 元素
 * @param {Object} id 盒子id
 * @param {Object} option 配置项
 * @param {Object} theme 主题
 * @param {Object} type 类型 map:地图
 * @param {Object} interval 轮播时间 默认2000
 * @param {Object} IsClear 重绘前是否清除
 */
const initChart = ({
  chart,
  element,
  chartBox,
  id = 'chartBox',
  option,
  theme,
  type,
  interval = 2000,
  loopShow = false,
  IsClear = false,
  IsResize = false,
}: {
  chart?: any
  element?: any
  chartBox?: any
  id?: string
  option?: any
  theme?: string
  type?: string
  interval?: number
  loopShow?: boolean
  IsClear?: boolean
  IsResize?: boolean
}) => {
  if (!chart) {
    chart = echarts.init(
      chartBox?.value || chartBox || element || document.getElementById(id),
      theme || '',
    )
  }
  if (IsClear) chart.clear()
  chart.setOption(option)
  let { $tools } = window
  if (loopShow && $tools && $tools.loopShowTooltip && type !== 'map') {
    if (chart.clearLoop) chart.clearLoop()
    chart.clearLoop = $tools.loopShowTooltip(chart, option, {
      loopSeries: true,
      interval,
    }).clearLoop
  }
  if (IsResize) chart.resize()
  return chart
}

/**
 * 移除 echart
 * @param {Object} chart
 */
const removeChart = (chart: any) => {
  if (!chart) return
  if (chart.chart) {
    if (chart.chart.clearLoop) chart.chart.clearLoop()
    chart.chart.dispose()
    return
  }
  if (chart.chart !== undefined) return
  if (chart.clearLoop) chart.clearLoop()
  chart.dispose()
}

let $echarts = Object.assign({}, echarts, { removeChart, initChart })

export default $echarts
